// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.rcp.intro;

import java.util.Arrays;
import java.util.List;

import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.prefs.IDenguesPrefsConstant;
import org.dengues.designer.ui.menu.ShowViewAction;
import org.dengues.designer.ui.menu.SwitchProjectAction;
import org.dengues.rcp.i18n.Messages;
import org.dengues.ui.toobar.AnnouncementContributionItem;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarContributionItem;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.NewProjectAction;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.internal.IWorkbenchHelpContextIds;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.registry.ActionSetRegistry;
import org.eclipse.ui.internal.registry.IActionSetDescriptor;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-12-5 qiang.zhang $<br/> An action bar advisor is responsible for creating, adding, and
 * disposing of the actions added to a workbench window. Each window will be populated with new actions.
 */
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {

    /**
     * Qiang.Zhang.Adolf@gmail.com ApplicationActionBarAdvisor class global comment. Detailled comment <br/>
     * 
     * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
     * 
     */
    class OpenDenguesPreferencesAction extends Action implements IWorkbenchAction {

        /**
         * The workbench window; or <code>null</code> if this action has been <code>dispose</code>d.
         */
        private IWorkbenchWindow workbenchWindow;

        /**
         * Create a new <code>OpenPreferenceAction</code> This default constructor allows the the action to be called
         * from the welcome page.
         */
        public OpenDenguesPreferencesAction() {
            this(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
        }

        /**
         * Create a new <code>OpenPreferenceAction</code> and initialize it from the given resource bundle.
         * 
         * @param window
         */
        public OpenDenguesPreferencesAction(IWorkbenchWindow window) {
            super(Messages.getString("ApplicationActionBarAdvisor.pref.text")); //$NON-NLS-1$
            if (window == null) {
                throw new IllegalArgumentException();
            }
            this.workbenchWindow = window;
            // @issue action id not set
            setToolTipText(Messages.getString("ApplicationActionBarAdvisor.pref.text")); //$NON-NLS-1$
            window.getWorkbench().getHelpSystem().setHelp(this, IWorkbenchHelpContextIds.OPEN_PREFERENCES_ACTION);
            setId("Preferences"); //$NON-NLS-1$
        }

        @Override
        public void run() {
            if (workbenchWindow == null) {
                // action has been dispose
                return;
            }
            PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(null, IDenguesPrefsConstant.DENGUES_PREF_ID, null,
                    null);
            dialog.open();
        }

        /*
         * (non-Javadoc) Method declared on ActionFactory.IWorkbenchAction.
         */
        public void dispose() {
            workbenchWindow = null;
        }
    }

    // Actions - important to allocate these only in makeActions, and then use
    // them
    // in the fill methods. This ensures that the actions aren't recreated
    // when fillActionBars is called with FILL_PROXY.
    private IWorkbenchWindow window;

    private IWorkbenchAction exitAction;

    private IWorkbenchAction aboutAction;

    private IWorkbenchAction newFileAction;

    private IWorkbenchAction helpContentsAction;

    private IWorkbenchAction introAction;

    private IWorkbenchAction saveAction;

    // private IWorkbenchAction showViewMenuAction;

    // private IWorkbenchAction maxAction;

    private IWorkbenchAction prefsAction;

    private IWorkbenchAction undoAction;

    private IWorkbenchAction redoAction;

    private IWorkbenchAction cutAction;

    private IWorkbenchAction copyAction;

    private IWorkbenchAction pasteAction;

    private IWorkbenchAction deleteAction;

    private IWorkbenchAction selectAll;

    /**
     * Qiang.Zhang.Adolf@gmail.com ApplicationActionBarAdvisor constructor comment.
     * 
     * @param configurer
     */
    public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
        super(configurer);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.ui.application.ActionBarAdvisor#makeActions(org.eclipse.ui.IWorkbenchWindow)
     */
    @Override
    protected void makeActions(final IWorkbenchWindow window) {
        // Creates the actions and registers them.
        // Registering is needed to ensure that key bindings work.
        // The corresponding commands keybindings are defined in the plugin.xml
        // file.
        // Registering also provides automatic disposal of the actions when
        // the window is closed.
        this.window = window;
        exitAction = ActionFactory.QUIT.create(window);
        register(exitAction);

        saveAction = ActionFactory.SAVE.create(window);
        register(saveAction);

        introAction = ActionFactory.INTRO.create(window);
        register(introAction);

        aboutAction = ActionFactory.ABOUT.create(window);
        register(aboutAction);

        newFileAction = ActionFactory.NEW.create(window);
        register(newFileAction);

        helpContentsAction = ActionFactory.HELP_CONTENTS.create(window);
        register(helpContentsAction);

        // showViewMenuAction = ActionFactory.SHOW_VIEW_MENU.create(window);
        // register(showViewMenuAction);
        //
        // maxAction = ActionFactory.MAXIMIZE.create(window);
        // register(maxAction);

        prefsAction = new OpenDenguesPreferencesAction(window);
        register(prefsAction);

        undoAction = ActionFactory.UNDO.create(window);
        register(undoAction);
        redoAction = ActionFactory.REDO.create(window);
        register(redoAction);
        cutAction = ActionFactory.CUT.create(window);
        register(cutAction);
        copyAction = ActionFactory.COPY.create(window);
        register(copyAction);
        pasteAction = ActionFactory.PASTE.create(window);
        register(pasteAction);
        deleteAction = ActionFactory.DELETE.create(window);
        register(deleteAction);
        selectAll = ActionFactory.SELECT_ALL.create(window);
        register(selectAll);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.ui.application.ActionBarAdvisor#fillMenuBar(org.eclipse.jface.action.IMenuManager)
     */
    @Override
    protected void fillMenuBar(IMenuManager menuBar) {
        MenuManager fileMenu = new MenuManager(
                Messages.getString("ApplicationActionBarAdvisor.File"), IWorkbenchActionConstants.M_FILE); //$NON-NLS-1$
        MenuManager editMenu = new MenuManager(
                Messages.getString("ApplicationActionBarAdvisor.Edit"), IWorkbenchActionConstants.M_EDIT); //$NON-NLS-1$
        MenuManager helpMenu = new MenuManager(
                Messages.getString("ApplicationActionBarAdvisor.Help"), IWorkbenchActionConstants.M_HELP); //$NON-NLS-1$
        MenuManager windowMenu = new MenuManager(
                Messages.getString("ApplicationActionBarAdvisor.Window"), IWorkbenchActionConstants.M_WINDOW); //$NON-NLS-1$

        menuBar.add(fileMenu);
        // Add a group marker indicating where action set menus will appear.
        menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        menuBar.add(editMenu);
        menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        menuBar.add(windowMenu);
        menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        menuBar.add(helpMenu);

        // File

        MenuManager newMeun = new MenuManager(Messages.getString("ApplicationActionBarAdvisor.New")); //$NON-NLS-1$
        newMeun.add(new NewProjectAction(window));
        newMeun.add(new Separator());
        newMeun.add(newFileAction);

        fileMenu.add(newMeun);
        fileMenu.add(saveAction);
        fileMenu.add(new Separator());
        fileMenu.add(new SwitchProjectAction());
        fileMenu.add(exitAction);
        // Edit
        editMenu.add(undoAction);
        editMenu.add(redoAction);
        editMenu.add(cutAction);
        editMenu.add(copyAction);
        editMenu.add(pasteAction);
        editMenu.add(deleteAction);
        editMenu.add(selectAll);

        // Window
        windowMenu.add(new ShowViewAction());
        // windowMenu.add(showViewMenuAction);
        // windowMenu.add(maxAction);
        windowMenu.add(new Separator());
        windowMenu.add(prefsAction);
        // Help
        // helpMenu.add(introAction);
        helpMenu.add(aboutAction);
        helpMenu.add(ActionFactory.HELP_CONTENTS.create(window));
    }

    private static final String[] ACTIONSETID = new String[] { "org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo", //$NON-NLS-1$
            "org.eclipse.ui.edit.text.actionSet.annotationNavigation", "org.eclipse.ui.NavigateActionSet", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.ui.WorkingSetActionSet", "org.eclipse.ui.edit.text.actionSet.navigation", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.search.searchActionSet", "org.eclipse.ui.edit.text.actionSet.openExternalFile", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.jdt.ui.actions.GoToPackage", "org.eclipse.jdt.ui.actions.GoToType", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.jdt.ui.actions.OpenExternalJavaDoc", "org.eclipse.jdt.ui.actions.OpenSuperImplementation", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.jdt.ui.actions.CopyQualifiedName", "org.eclipse.jdt.ui.actions.Open", //$NON-NLS-1$ //$NON-NLS-2$
            "org.eclipse.jdt.ui.actions.OpenTypeHierarchy", "org.eclipse.jdt.ui.actions.OpenCallHierarchy" }; //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.ui.application.ActionBarAdvisor#fillCoolBar(org.eclipse.jface.action.ICoolBarManager)
     */
    @Override
    protected void fillCoolBar(ICoolBarManager coolBar) {
        IToolBarManager toolbar = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
        coolBar.add(new ToolBarContributionItem(toolbar, "dengues")); //$NON-NLS-1$

        toolbar.add(DenguesCorePlugin.getDefault().getDesignerUIService().getLaunchEditorAction());
        toolbar.add(DenguesCorePlugin.getDefault().getDesignerUIService().getStopEditorAction());

        toolbar = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
        coolBar.add(new ToolBarContributionItem(toolbar, "hsqldb")); //$NON-NLS-1$
        Action dataBaseAction = DenguesCorePlugin.getDefault().getDesignerCoreService().createStartHsqldbServer();
        // = new RunDataBaseAction();
        Action optionHsqldb = DenguesCorePlugin.getDefault().getWarehousePluginService().getOptionHsqldb();
        dataBaseAction.setEnabled(true);
        optionHsqldb.setEnabled(true);

        toolbar.add(dataBaseAction);
        toolbar.add(optionHsqldb);

        toolbar = new ToolBarManager(SWT.FLAT | SWT.LEFT);
        coolBar.insertAfter("hsqldb", new ToolBarContributionItem(toolbar, "ads")); //$NON-NLS-1$ //$NON-NLS-2$
        AnnouncementContributionItem announcementItem = new AnnouncementContributionItem(Messages
                .getString("ApplicationActionBarAdvisor.message"));
        toolbar.add(announcementItem); //$NON-NLS-1$

        ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry();
        IActionSetDescriptor[] actionSets = reg.getActionSets();
        List list = Arrays.asList(ACTIONSETID);
        for (int i = 0; i < actionSets.length; i++) {
            if (list.contains(actionSets[i].getId())) {
                removeAction(reg, actionSets[i]);
            }
        }
    }

    private void removeAction(final ActionSetRegistry reg, final IActionSetDescriptor actionSet) {
        IExtension ext = actionSet.getConfigurationElement().getDeclaringExtension();
        reg.removeExtension(ext, new Object[] { actionSet });
    }
}
